using System;namespace CWHomeWebSite.Models{ public class PagingInfo { //项目总数量 public int TotalItems { get; set; } //当前索引 public int PageIndex { get; set; } //分页大小 public int PageSize { get; set; } //页数 public int PageCount { get { return (int)Math.Ceiling((decimal)TotalItems / PageSize); } } }}
创建视图对应的ViewModel
using CWHomeWebSite.Data.Entities;using System.Collections.Generic;namespace CWHomeWebSite.Models{ public class PostViewModel { //博客集合 public IEnumerablePosts { get; set; } //分页参数 public PagingInfo PagingInfo { get; set; } }}
处理Controller视图方法
public ActionResult Index(int pageIndex = 1, int pageSize = 2) { //获取当前分页数据集合 var posts = this.repository.Posts .OrderBy(p=>p.UpdateTime) .Skip((pageIndex - 1) * pageSize) .Take(pageSize); //将当前ViewModel传递给视图 return View(new PostViewModel { Posts = posts, PagingInfo = new PagingInfo { TotalItems = this.repository.Posts.Count(), PageIndex = pageIndex, PageSize = pageSize } }); }
在View中通过Html辅助器扩展方法处理PagingInfo
using CWHomeWebSite.Models;using System;using System.Web.Mvc;namespace CWHomeWebSite.Helper{ public static class PagingHelper { //HtmlHelper扩展方法,用于分页 public static MvcHtmlString Pagination(this HtmlHelper html, PagingInfo pageInfo,FuncpageLinks) { var htmlString = pageLinks(pageInfo); return MvcHtmlString.Create(htmlString); } }}
@model CWHomeWebSite.Models.PostViewModel@using CWHomeWebSite.Helper@{ ViewBag.Title = "主页";}@Html.Action("RecentWorks", "Work") @foreach (var post in Model.Posts) {
@Html.Pagination(Model.PagingInfo, (info) => { var pagingString = " "; return pagingString; })- }
@post.Title | @post.CreateTime.ToShortDateString()
@post.Description
- @Html.ActionLink("更多", "Detail", "Home", new { @post.PostId }, new { @class = "button" })
url跳转:
@Url.Action("Index", "Home", new { id=1})“生成的html是:”生成的url为: /Home/Index/1“